package com.crazymaker.demo.hystrix;

import com.crazymaker.springcloud.standard.utils.HttpRequestUtil;
import com.netflix.hystrix.HystrixCommand;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class HttpGetterCommand extends HystrixCommand<String>
{

    private String url;
    //run 方法 是否执行
    private boolean isRun = false;
    //执行的次序
    private int index;
    //执行的总次数，线程安全
    private static AtomicInteger count = new AtomicInteger(0);

    public HttpGetterCommand(String url, Setter setter)
    {
        super(setter);
        this.url = url;
    }

    @Override
    protected String run() throws Exception
    {
        isRun = true;
        index = count.incrementAndGet();
        log.info(" 第{}次请求-> begin......", index);
        try
        {
            Thread.sleep(2000);//这里让线程等待2s，保持线程不释放
        } catch (Exception e)
        {
            e.printStackTrace();
        }


        String responseData = HttpRequestUtil.simpleGet(url);

        log.info(" 第{}次请求-> end！", index);
        return responseData;
    }

    @Override
    protected String getFallback()
    {
        if (!isRun)
        {
            index = count.incrementAndGet();
        }

        //是否直接失败
        boolean isFastFall = !isRun;
        //断路器是否打开
        boolean isCircuitBreakerOpen = isCircuitBreakerOpen();
        log.info(" 第{}次调用,熔断打开->{},直接失败->{},fallBack->{}",
                index,
                isCircuitBreakerOpen,
                isFastFall,
                url);

        return "fallBack->" + url;
    }

}